
//
//  ledblink.c
//  Senior Project
//
//  Created by Keegan Kilroy on 9/27/11.
//  Copyright 2011 University of Maine. All rights reserved.
//
#define F_CPU 1000000UL
#define BAUD 9600
#include <avr/io.h>
#include <avr/iom48.h>
#include <util/delay.h>
#include <stdlib.h>
#define ENB 0x04
#define IN3 0x08
#define IN4 0x10
#define RX  0x01
#define TX  0x02

#define D .5 /* ms */
void usart_init(void);
void usart_putc(unsigned char c);
unsigned char usart_getc(void);
void goleft(int a);
void goright(int a);
unsigned char getadc( unsigned char input);

int main(void){
    DDRC=0x00;      // set PORTC to output pins
    DDRD = 0xFF;    // set PORTD to input pins
    //ADMUX = 0b10100001; // sets AVCC as ref voltabe and ADCH as 8msb and ADCL as 2lsb
                        // and sets PC0 as the input
    

    //usart_init();
    
    PORTD = 0x00;
    
/******************
        MAIN
 ******************/
    
while(1){
    
    
    /* unsigned char tmp;
    PORTD = IN4;
    tmp = usart_getc();
    PORTD = IN3;
    usart_putc(tmp);*/
    
    //usart_putc(usart_getc());
    
    
    
    
    
    
    int a=1, b, c;
 
    
        
    if (PINC & 0b00000001){
        
        goleft(a);
    }
    //else if (PINC != 0b00000001){ 
        //goright(a);
    //}
    
    //PORTD = 0x00;
        
    
}

    return 0;
}


/********************
    SUB-ROUTINES
 ********************/



void goright(int a){
    int i;
    
    for(i=0;i<a;i++){ // PWM
        PORTD = (IN4 | ENB ); // enable h bridge while doing pwm
		_delay_ms(D);
		PORTD = (!IN4 | ENB);
		_delay_ms(D);
    }
    PORTD = 0x00;

}
void goleft(int a){
    int i;
 
    for(i=0;i<a;i++){ // PWM
        PORTD = (IN3 | ENB); // enable h bridge while doing pwm
       _delay_ms(D);
        PORTD = (!IN3 | ENB);
        _delay_ms(D);
    }
    PORTD = 0x00; // dis enable the H-Bridge
 
}

//unsigned char getadc( unsigned char input){
    //ADCH = 0x00; // clear previous 
    
    
//}
void usart_init(void){
    UBRR0H = 0; // splits ubrr into upper and lower
    UBRR0L = 12;
    

    UCSR0B |= (1 << RXEN0)|(1 << TXEN0); // enables receive and transmit bits
    UCSR0C |= (0 << USBS0) | (3 << UCSZ00); // makes 8 bit, 1 stop bit and no parity
    UCSR0A |= (1 <<U2X0);
    PORTD = (IN3 | IN4 );
    _delay_ms(500);
    PORTD = !(IN3 | IN4 );
    _delay_ms(500);
    
}

void usart_putc(unsigned char c){
    while (!(UCSR0A & (1<< UDRE0))  ) ; // checks UDRE0 flag to see if the register is empty
        UDR0 = c; // data is put in UDR0
    
}
unsigned char usart_getc(void){
    while (!(UCSR0A & (1<<RXC0)) ); // waits for data from avr
        return UDR0; // returns the data
}
